<template>
  <div class="app-container">
    <!-- 树形结构 -->
    <el-tree :expand-on-click-node="false" default-expand-all :data="depts" :props="defaultProps">
      <!-- 节点结构 -->
      <template v-slot="{ data }">
        <el-row style="width: 100%; height: 40px;" type="flex" justify="space-between" align="center">
          <el-col> {{ data.name }}</el-col>
          <el-col :span="4">
            <span class="manager">{{ data.managerName?.replace('黑马', '') || '无负责人' }}</span>
            <el-dropdown @command="operateDept($event, data.id)">
              <span>操作<i /></span>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item command="add">添加子部门</el-dropdown-item>
                <el-dropdown-item command="edit">编辑部门</el-dropdown-item>
                <el-dropdown-item command="del">删除</el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
          </el-col>
        </el-row>
      </template>
    </el-tree>
    <!-- 添加部门弹窗 .sync自动监听事件  ref:父组件调用子组件的方法-->
    <add-dept ref="addDept" :current-node-id="currentNodeId" @updateDepartment="getDepartment"
      :show-dialog.sync="showDialog" />
  </div>
</template>

<script>
import { getDepartment, deleteDepartment } from '@/api/department'// 导入接口(数据获取)
import { transListToTreeData } from '@/utils'
import AddDept from '@/views/department/components/add-dept.vue'
export default {
  name: 'Department', // 组件名称
  components: { AddDept },
  data() {
    return {
      currentNodeId: null,// 当前节点id,用于添加子部门时记录父节点id，方便后端处理
      showDialog: false, // 默认隐藏添加部门弹窗
      depts: [], // 树形数据
      // 树形结构配置
      defaultProps: {
        label: 'name', // 显示字段名
        children: 'children' // 子节点字段名
      }
    }
  },
  // 在组件加载时自动调用 getDepartment,无需手动调用
  created() {
    this.getDepartment()
  },
  // 封装数据获取逻辑，便于复用。比如，除了 created，某个用户操作（如按钮点击）也可能需要获取数据时调用这个方法。
  methods: {
    async getDepartment() {
      const result = await getDepartment()
      this.depts = transListToTreeData(result, 0)
    },
    // 操作功能
    operateDept(type, id) {
      if (type === 'add') {
        this.showDialog = true
        this.currentNodeId = id
      }
      else if (type === 'edit') {
        this.showDialog = true
        this.currentNodeId = id
        // 展示部门详情，nextTick是为了保证弹窗渲染完成后再展示部门详情
        this.$nextTick(() => {
          this.$refs.addDept.getDepartmentDetail()//调用子组件add-dept.vue中的方法，获取部门详情
        })
      } else {
        this.$confirm('此操作将永久删除该部门, 是否继续?').then(async () => {
          await deleteDepartment(id)
          this.$message.success('删除成功')
          this.getDepartment()
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
      }
    },
  }


}
</script>

<style scoped>
.app-container {
  padding: 30px 148px;
  /* 内边距 */
  font-size: 14px;
  /* 字体大小 */
}

.el-col {
  padding: 14px;
}

.manager {
  width: 50px;
  display: inline-block;
}
</style>
